<?php

namespace app\admin\controller\product;

use app\common\controller\Backend;

class Product extends Backend
{
    // 设置关联查询
    protected $relationSearch = true;

    // 当前模型
    protected $model = null;

    // 无需登陆
    protected $noNeedLogin = [];
    // 无需鉴权
    protected $noNeedRight = [];

    public function __construct(){
        parent::__construct();

        $this->model = model('Product.Product');
        $this->TypeModel = model('Product.Type');
        $this->UnitModel = model('Product.Unit');

        $FlagList = [1=>'新品',2=>'热销',3=>'推荐'];
        $TypeList = $this->TypeModel->column('id,name');
        $UnitList = $this->UnitModel->column('id,name');
        $StatusList = [0=>'下架',1=>'上架'];

        // var_dump($TypeList);
        // exit;
        $this->assign([
            'FlagList' => $FlagList,
            'TypeList' => $TypeList,
            'UnitList' => $UnitList,
            'StatusList' => $StatusList
        ]);
    }


    public function index(){
        // 将请求中的html标签和空白都去掉
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if($this->request->isAjax()){
            list($where,$sort,$order,$offset,$limit) = $this->buildparams();

            // 表格两个返回值
            $total = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort,$order)
                ->count();

            $list = $this->model
                ->with(['type','unit'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();
            
            // var_dump(collection($list)->toArray());
            // exit;

            $result = [
                'total' => $total,
                'rows' => $list
            ];

            
            return json($result);
        }

        return $this->view->fetch();
    }

    public function add(){
        if($this->request->isPost()){
            $params = $this->request->param('row/a');

            $data = [
                'name' => $params['name'],
                'content' => $params['content'],
                'flag' => $params['flag'],
                'status' => $params['status'],
                'stock' => $params['stock'],
                'typeid' => $params['typeid'],
                'unitid' => $params['unitid'],
                'price' => $params['price'],
                'thumbs' => $params['thumbs']
            ]; 

            $result = $this->model->validate('common/Product/Product')->save($data);

            if($result === FALSE){
                $this->error($this->model->getError());
                exit;
            }else{
                $this->success('添加商品成功');
                exit;
            }
        }

        // 先将商品分类查询出来
        $typelist = $this->TypeModel->column('id,name');
        $this->assign('typelist',build_select('row[typeid]',$typelist,[],['class'=>'selectpicker','required'=>'']));

        // 先将单位查询出来
        $unitlist = $this->UnitModel->column('id,name');
        $this->assign('unitlist',build_select('row[unitid]',$unitlist,[],['class'=>'selectpicker','required'=>'']));

        return $this->view->fetch();
    }

    public function edit($ids=NULL){
        $row = $this->model->find($ids);
        if(!$row){
            $this->error(__('No Results were found'));
            exit;
        }

        if($this->request->isPost()){
            $params = $this->request->param('row/a');

            $data = [
                'id' => $ids,
                'name' => $params['name'],
                'content' => $params['content'],
                'flag' => $params['flag'],
                'status' => $params['status'],
                'stock' => $params['stock'],
                'typeid' => $params['typeid'],
                'unitid' => $params['unitid'],
                'price' => $params['price'],
                'thumbs' => $params['thumbs']
            ]; 

            $result = $this->model->validate('common/Product/Product')->isUpdate()->save($data);

            if($result === FALSE){
                $this->error($this->model->getError());
                exit;
            }else{
                if($data['thumbs'] != $row['thumbs']){
                    is_file('.'.$row['thumbs']) && @unlink('.'.$row['thumbs']);
                }
                $this->success('编辑商品成功');
                exit;
            }
        }

        // 先将商品分类查询出来
        $typelist = $this->TypeModel->column('id,name');
        $this->assign('typelist',build_select('row[typeid]',$typelist,$row['typeid'],['class'=>'selectpicker','required'=>'']));

        // 先将单位查询出来
        $unitlist = $this->UnitModel->column('id,name');
        $this->assign('unitlist',build_select('row[unitid]',$unitlist,$row['unitid'],['class'=>'selectpicker','required'=>'']));

        $this->assign('row',$row);
        return $this->view->fetch();
    }

    public function del($ids=NULL){
        $ids = $this->request->param('ids',[],'trim');
        $list = $this->model->where(['id' => ['IN',$ids]])->select();
        // var_dump(collection($list)->toArray());
        // exit;

        if(!$list){
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->destroy($ids);

        if($result === FALSE){
            $this->error('删除失败');
            exit;
        }else{
            $this->success('删除成功');
            exit;
        }
    }

    // 回收站
    public function recyclebin(){
        $this->request->filter(['strip_tags','trim']);

        if($this->request->isAjax()){
            //获取表格所提交过来筛选和排序的一些参数
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            // 表格需要两个返回值参数 总条数和分页的数据
            $total = $this->model
                ->onlyTrashed()
                ->with(['type','unit'])
                ->where($where)
                ->order($sort,$order)
                ->count(); //返回查询的总数

            // var_dump($total);
            // exit;
            $list = $this->model
                ->onlyTrashed()
                ->with(['type','unit'])
                ->where($where)
                ->order($sort,$order)
                ->limit($offset,$limit)
                ->select();
            // var_dump(collection($list)->toArray());
            // exit;

            // 打印sql语句
            // echo $this->model->getLastSql();
            // exit;

            // 组装数据
            $result = [
                'total' => $total,
                'rows' => $list
            ];
            // 返回给ajax的数据
            return json($result);  

        }
        return $this->view->fetch();
    }

    // 恢复
    public function restore($ids=NULL){
        $ids = $ids ?: $this->request->param('ids',0,'trim');
        $rows = $this->model->onlyTrashed()->select($ids);
        // var_dump(collection($rows)->toArray());
        // exit;

        if(!$rows){
            $this->error(__('No Results were found'));
            exit;
        }

        $result = $this->model->onlyTrashed()->where(['id'=>['IN',$ids]])->update(['deletetime'=>NULL]);

        if($result === FALSE){
            $this->error('恢复数据失败');
            exit;
        }else{
            $this->success('恢复数据成功');
            exit;
        }
    }

    // 销毁
    public function destroy($ids=NULL){
        $ids = $ids ?: $this->request->param('ids',0,'trim');
        $rows = $this->model->onlyTrashed()->select($ids);
        // var_dump(collection($rows)->toArray());
        // exit;

        if(!$rows){
            $this->error(__('No Results were found'));
            exit;
        }

        // 删除图片
        // 从数据中提取出thumbs这个字段的值
        $thumbs = array_column($rows,"thumbs");

        // 去重、去空
        $thumbs = array_filter($thumbs);
        $thumbs = array_unique($thumbs);

        $result = $this->model->onlyTrashed()->where(['id'=>['IN',$ids]])->delete(true);

        if($result === FALSE){
            $this->error('销毁商品失败');
            exit;
        }else{
            if(!empty($thumbs)){
                foreach($thumbs as $item){
                    is_file(".".$item) && @unlink(".".$item);
                }
            }
            $this->success('销毁商品成功');
            exit;
        }
    }
    
}
